package com.example.testmarkwon

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class MainActivityViewModel : ViewModel() {

    private var rawText: String = ""
    private var rawFrame: Int = 0

    private val _text = MutableStateFlow("")
    val text = _text.asStateFlow()

    private val _currentFrame = MutableStateFlow("")
    val currentFrame = _currentFrame.asStateFlow()

    fun updateText(text: String) {
        rawText = text
        updateCurrentFrame(0)
        updateMarkdownResult()
    }

    fun goPrev() {
        val dst = rawFrame - 1
        updateCurrentFrame(dst)
        updateMarkdownResult()
    }

    fun goNext() {
        val dst = rawFrame + 1
        updateCurrentFrame(dst)
        updateMarkdownResult()
    }

    fun goStart() {
        updateCurrentFrame(0)
        updateMarkdownResult()
    }

    fun goEnd() {
        updateCurrentFrame(rawText.length)
        updateMarkdownResult()
    }

    private fun updateCurrentFrame(dst: Int) {
        if (dst in 0 .. rawText.length) {
            rawFrame = dst
        }
        _currentFrame.value = "${rawFrame}/${rawText.length}"
    }

    private fun updateMarkdownResult() {
        val result = rawText.substring(0, rawFrame)
        _text.value = result
    }
}